package cli;

import util.Constant;

import java.io.File;
import java.util.*;

public class CommandLineParser {

    private static boolean checkTestFile(CommandLineOptions options) {
        System.out.println("Start to check test apk files");
        String testFilePath = options.getTestPath();
        if (testFilePath == null) {
            System.err.println("Test file path is null");
            return false;
        }

        File testFile = new File(testFilePath);
        // 不存在
        if (!testFile.exists()) {
            System.err.println("File or directory not found: " + testFilePath);
            return false;
        }

        // 单个文件
        if (testFile.isFile()) {
            System.out.println("Input a single file");
            if (!Constant.isLegalApkFile(testFile)) {
                System.err.println("Test file should ends with '.apk' suffix, while input is: " + testFilePath);
                return false;
            }
            System.out.println("[Input] Valid testFile: ");
            System.out.println(testFile.getName());
            options.map.put(testFile.getAbsolutePath(), null);
            return true;
        }
        // 目录
        else if (testFile.isDirectory()) {
            System.out.println("Input a directory");
            List<File> collect = Arrays.stream(Objects.requireNonNull(testFile.listFiles())).filter(Constant::isLegalApkFile).toList();
            if (collect.size() == 0) {
                System.err.println("No .apk file found in the dir: " + testFilePath);
                return false;
            }
            System.out.println("[Input] Valid testFile:");
            collect.forEach(file -> {
                System.out.println(file.getName());
                options.map.put(file.getAbsolutePath(), null);
            });
            return true;
        }
        return false;
    }

    private static boolean checkOptionsValid(CommandLineOptions options) {
        // check Test Apk
        return checkTestFile(options);
    }

    public static CommandLineOptions parseArgs(String[] args) {
        CommandLineOptions options = new CommandLineOptions();

        for (String arg : args) {
            options.setTestPath(arg);
        }
        boolean valid = checkOptionsValid(options);
        return valid ? options : null;
    }
}

